package sample.ui

import android.app.Dialog
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.core.view.updateLayoutParams
import androidx.fragment.app.FragmentManager
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.netease.core.R
import kotlinx.coroutines.script.tes.ServerApi
import kotlinx.coroutines.script.tes.appContext
import kotlinx.coroutines.script.tes.appDeviceInfo
import kotlinx.coroutines.script.tes.appVersionName
import kotlinx.coroutines.script.tes.closeKeyboard
import kotlinx.coroutines.script.tes.dp
import kotlinx.coroutines.script.tes.phoneDefaultDisplayPoint
import kotlinx.coroutines.script.tes.phoneScreenWidth
import kotlinx.coroutines.script.tes.printLog
import kotlinx.coroutines.script.tes.setOnClickCallback
import kotlinx.coroutines.script.tes.systemWindowInsetsTop
import kotlinx.coroutines.script.tes.toTime
import kotlin.math.floor

class CKV2SetupDialogFragment: BottomSheetDialogFragment() {
    private val peekHeight get() = (phoneDefaultDisplayPoint.y - (10.dp) - systemWindowInsetsTop)

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        return super.onCreateDialog(savedInstanceState).apply {
            setCanceledOnTouchOutside(true)
            window?.setLayout(phoneScreenWidth, peekHeight)
            window?.setGravity(Gravity.BOTTOM)
            window?.setWindowAnimations(R.style.Animation_Bottom_Rising)
            window?.decorView?.setPadding(0, 0, 0, 0)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NORMAL, R.style.BottomSheetDialog)
    }

    override fun onStart() {
        super.onStart()
        val behavior = ((view?.parent) as FrameLayout?)?.let { BottomSheetBehavior.from(it) }
        behavior?.peekHeight = peekHeight
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        return LayoutInflater.from(context).inflate(R.layout.ckv2sf, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        view.updateLayoutParams { height = peekHeight }
        view.setOnClickCallback { closeKeyboard() }
        view.findViewById<View>(R.id.close).setOnClickCallback {
            dismissAllowingStateLoss()
        }
        view.findViewById<View>(R.id.importCkV2).setOnClickCallback {
            SetupCKV2Dialog.Builder(it.context)
                .setCallback(object : SetupCKV2Dialog.OnCDKeyInputListener {
                    override fun onInput(value: String) {
                        // 这里做接口请求验证了
                        printLog { "SetupCKV2Dialog onInput $value" }
                        ServerApi.requestActivate(value)
                    }
                }).create().show()
        }
        ServerApi.apiLoading.observe(this) {
            view.findViewById<View>(R.id.loading).isVisible = it
            view.findViewById<View>(R.id.importCkV2).also { view ->
                view.isEnabled = !it
                view.alpha = if (it) 0.6f else 1f
            }
        }
        ServerApi.apiRespResult.observe(this) {
            it?.also {
                // 这里如果成功了.返回的就是卡的信息
                Properties.setCKV2Info(it)

                val clipboard = appContext.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
                val clipData = ClipData.newPlainText(null, it.value ?: "")
                clipboard.setPrimaryClip(clipData) // 激活后 卡密放到剪切板

                update()
                Permissions.updateCDKeyActivating()
                ServerApi.apiRespResult.value = null
            }
        }
        Permissions.statusUpdated.observe(viewLifecycleOwner) {
            it?.also { update() }
        }
        printLog { appDeviceInfo }
    }

    override fun onResume() {
        super.onResume()
        update()
    }

    private fun update() {
        view?.findViewById<TextView>(R.id.deviceIdView)?.text = Properties.ckV2Info?.value
        view?.findViewById<TextView>(R.id.moreInfo)?.also {
            it.isVisible = Properties.ckV2Info != null
            it.text = Spanner().also { text ->
                text.append("激活时间 ${Properties.ckV2Info?.activeTime?.toTime("yyyy/MM/dd HH:mm")}")
                text.append("\n")
                text.append("有效期至 ${Properties.ckV2Info?.expirationTime?.toTime("yyyy/MM/dd HH:mm")}")
                text.append("\n")
                val expiredTs = Properties.ckV2Info?.expirationTime
                if (expiredTs != null) {
                    val remainingTime = expiredTs - System.currentTimeMillis()
                    val left = if (remainingTime > 0) {
                        val days = floor((remainingTime / (1000 * 60 * 60 * 24)).toDouble()).toInt()
                        val hours = floor(((remainingTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)).toDouble()).toInt()
                        if (days > 0) "剩余${days}天${hours}小时\n"
                        else if (hours > 0) "剩余${hours}小时\n"
                        else "即将失效"
                    } else "已失效"
                    text.append(left)
                }
            }
        }
        view?.findViewById<View>(R.id.moreInfoTitle)?.isVisible = Properties.ckV2Info != null
        view?.findViewById<TextView>(R.id.versionInfo)?.text = "v.$appVersionName"
    }

    fun show(fragmentManager: FragmentManager?) {
        if (fragmentManager == null || fragmentManager.isStateSaved) return
        show(fragmentManager, this.javaClass.simpleName)
    }
}